import React, { Component } from "react";
import {
    StyleSheet,
    Text,
    View,
    Platform,
    TextInput,
    TouchableOpacity,
    DeviceEventEmitter,
    NativeAppEventEmitter,
    ScrollView,
    Switch,
    Button,
    InteractionManager,
  Dimensions
} from "react-native";

import Toast from "react-native-sk-toast";
import ImagePicker from 'react-native-image-picker';
import api from "../../services/api";
import _ from "lodash";
import moment from "moment";
import styles from "./serviceCompletionStyle";
import ToastTip from "../global/ToastTip";
import LoadingTip from "../global/LoadingTip";
import dismissKeyboard from "dismissKeyboard";
import * as config from "../../constants/apiConfig";
import { Navigation } from '../global/navigation/index';
const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');
// import Touch from '../global/Touch';

class ServiceCompletion extends Component {
    constructor(props) {
        super(props);
        this.state = {
            obj_price: "",
            showLoading: false,
            btnDisabled: false,
            isPay: false,
            serviceCostDetail: "",
            serviceCost: ""
        };
    }

    componentDidMount(){
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        this._subcribOrder = Emitter.addListener('pop', this.pop.bind(this));
        // this._subcribHandSignSuccess = Emitter.addListener('hand.sign.success', this._handWritingSignSuccess.bind(this));
    }

    componentWillMount() {}

     componentWillUnmount(){
        this._subcribOrder && this._subcribOrder.remove();
        // this._subcribHandSignSuccess && this._subcribHandSignSuccess.remove();
        // let {actions, dispatch} = this.props;
        // await this._createSession();
    }

    pop(){
        setTimeout(()=>{
            console.log('test',"==========");
            this.props.navigator.pop();
            let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
            Emitter.emit("order.onload");
        }, 500);
    }
    // _handWritingSignSuccess(){
    //     console.log('test',"_handWritingSignSuccess_serviceCompletion");
    //     setTimeout(()=>{
    //     console.log('test',"_handWritingSignSuccess_serviceCompletion=========");
    //         this.props.navigator.pop();
    //     }, 500);
    // }

    async _submitAction() {
        let { order_info, session, navigator } = this.props;
        let { serviceCost,serviceCostDetail } = this.state;
        console.log('_submitAction--------------',order_info);
        // console.log("@@@", obj_price);

        if (!serviceCost) {
            this.refs.toast.show("请输入服务金额");
            return;
        }

        if (parseFloat(serviceCost) == 0) {
            this.refs.toast.show("请输入大于零的金额");
            return;
        }

        if (order_info.orderType == "nursing") {
            this._getObj(order_info,serviceCost,serviceCostDetail);
            return;
        }

        this.setState({ showLoading: true, btnDisabled: true });

        // let send_res = await api.post("/wx/customsend");
        if (order_info.orderType == "express") {
            this._addExpressFee(order_info,serviceCost,serviceCostDetail);
            return;
        }
        let res = await api.post("/order/setServiceCost",{id:order_info.id,serviceCost,serviceCostDetail});
        if (res.cd == 1){
            this.setState({ showLoading: false , btnDisabled: false});
            Toast.bottom(res.msg);
            return;
        }

        if(res.data){
            // let { actions, dispatch } = this.props;
            navigator.pop();
            let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                Emitter.emit("order.onload");

            // dispatch(
            //     actions.order.order_done_obj_price(order_info.id)
            // ).then(() => {
            //     this.setState({ showLoading: false });
            //
            // });

        }else{
            this.setState({ showLoading: false , btnDisabled: false});
            Toast.bottom("该笔订单已设置服务金额，请刷新后重试");
        }

    }

    async _addExpressFee(order_info,serviceCost,serviceCostDetail){
        console.log('test',order_info.id);
        let {navigator} = this.props;
        let res = await api.post("/order/setExpressCost",{id:order_info.id,expressCost:serviceCost,expressDetails:serviceCostDetail});
        if (res.cd == 1){
            this.setState({ showLoading: false , btnDisabled: false});
            Toast.bottom(res.msg);
            return;
        }

        navigator.pop();
            let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                Emitter.emit("order.onload");

        // this.setState({ showLoading: false , btnDisabled: false});

        // Toast.bottom("该笔订单已设置服务金额，请刷新后重试");
        // this._updateStatus(order_info);

        // if(res.data){
            // let { actions, dispatch } = this.props;
            
            // navigator.pop();
            // let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
            //     Emitter.emit("order.onload");

            // dispatch(
            //     actions.order.order_done_obj_price(order_info.id)
            // ).then(() => {
            //     this.setState({ showLoading: false });
            //
            // });

        // }else{
        // }
    }




    confirmService = async () => {
//             let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
// Emitter.emit("pop");
// 
        // let { actions, dispatch,navigator, order_info, changeBtn} = this.props;
        // dispatch(actions.order.order_done_obj_price(order_info.id)).then(() => {
        //     this.setState({ showLoading: false });
        //     // changeBtn?changeBtn():null;
        //     navigator.pop();
        // });
        // this.props.completeTask?this.props.completeTask():null;

        let { session, order_info} = this.props;
        this.setState({ completeActionDisabled: true });

        if (order_info.orderType == "nursing") {
            this._getObj(order_info);
            return;
        }
        this._updateStatus(order_info);

    };


    async _getObj(info,serviceCost,serviceCostDetail){

        var options = {
            title: '拍照获取物品照片',
            cancelButtonTitle: "取消",
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'选择相册',
            permissionDenied: {
              title: '提示',
              text: '没有拍照和获取相册权限',
              reTryTitle: '重试',
              okTitle: '确定',
            },
            quality: 0.8,
            maxHeight: parseInt(deviceHeight*2),
            maxWidth: parseInt(deviceWidth*2),
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        };
        // 照片
        ImagePicker.showImagePicker(options, (response)  => {
            // Same code as in above section!
            if (response.error) {
            }else{
                if (response.didCancel) {
                   return;
                }

                InteractionManager.runAfterInteractions(() => {
                    this.props.navigator.push({
                        title: '确认物品照片',
                        screen: 'housekeeperapp.imagepicker',
                        backButtonTitle:'',
                        passProps: {
                            from:'completion',
                            orderId: info.id,
                            orderType: info.orderType,
                            fileUri:response.uri,
                            otherServiceType:info.otherServiceType,
                            fileName:response.fileName,
                            status:info.status,
                            needPay:this.state.isPay,
                            serviceCost:serviceCost,
                            serviceCostDetail:serviceCostDetail,
                            orderPhone:info.user_phone
                            // source: 'data:image/jpeg;base64,' + response.data
                        },
                        navigatorStyle:{
                            tabBarHidden: true,
                            navBarTextColor: 'white',
                            navBarButtonColor: 'white',
                            navBarBackgroundColor: '#EA5404',
                            statusBarColor: '#EA5404',
                            navBarTitleTextCentered: true,
                            topBarElevationShadowEnabled:false
                        },
                        navigatorButtons: {
                            leftButtons:[
                                {
                                    id: 'back',
                                    icon: require("../../../img/hk_back_icon.png")
                                }
                            ]
                        }
                    });
                    this.props.navigator.pop();
                });

                // this.setState({
                //     showLoading:true,
                // })
            }

        });

    }

    // async _postPictureData(info,fileUri,fileName){
    //     let file = {uri:fileUri,name:fileName,type:'image/jpeg'}
    //     let result = await api.upload('/file/upload',file,'ORDER')
    //     if (result.cd == 0) {
    //         let images = []
    //         images.push(result.data.id)
    //         this._completeUpload(info,images);
    //     }else{
    //         this.setState({
    //             showLoading:false,
    //         })
    //         Toast.bottom("上传失败:"+result.msg);
    //     }
    // }

    // async _completeUpload(info,images){
    //     let result = await api.post('/order/uploadImage',{id:info.id,type:'ORDER_FINISH_IMAGE',images:images})
    //     if (result.cd == 0) {
    //         this._updateStatus(info);
    //     }else{
    //         this.setState({
    //             showLoading:false,
    //         })
    //         Toast.bottom("创建失败:"+result.msg);
    //     }
    // }

    async _updateStatus(order_info){
        let {session} = this.props;
        let res = await api.post("/order/updatestatus", {
            id: order_info.id,
            status: 4,
            cancelReason:''
        });

        if(res.cd == 1){
            Toast.bottom(res.msg);
            return;
        }

        if (res.data) {
            // let ownerInfo = await api.post("/housekeeper/ownerinfobyphone", {
            //     phone: order_info.user_phone
            // });


            // if (ownerInfo.data) {
            //     let send_text = "";
            //     let orderTrack = await api.post("/order/tracksdetail", {
            //         id: order_info.id
            //     });
            //     if (orderTrack.data) {
            //         let delayTime = (
            //             (moment(orderTrack.data.order_endsend_time) -
            //                 moment(orderTrack.data.order_hkget_time)) /
            //             60000
            //         ).toFixed(0);

            //         // let { session } = this.props;
            //         let web_base_url = "";
            //         if (session && session.user && session.user.product && session.user.product.baseUrl) {
            //             web_base_url = session.user.product.baseUrl;
            //         }else{
            //             web_base_url = config.WEB_BASE_URL;
            //         }


            //         if (order_info.orderType == 'other' && order_info.othertype == 'activity') {
            //             send_text =
            //                 "您的订单已完成。<a href='" +
            //                 web_base_url +
            //                 "/weichart/order?order_id=" +
            //                 order_info.id +
            //                 "&type=ORDER_REWARD&othertype="+order_info.othertype+"'>评价服务</a>";
            //         }else if (order_info.orderType == 'nursing') {
            //             send_text =
            //                 "您的订单已完成。<a href='" +
            //                 web_base_url +
            //                 "/weichart/order?order_id=" +
            //                 order_info.id +
            //                 "&type=ORDER_REWARD&othertype=nursing'>评价服务</a>";
            //         }else{
            //             send_text =
            //                 "您的订单已完成，耗时" +
            //                 delayTime +
            //                 "分钟。<a href='" +
            //                 web_base_url +
            //                 "/weichart/order?order_id=" +
            //                 order_info.id +
            //                 "&type=ORDER_REWARD&othertype="+order_info.othertype+"'>评价服务</a>";
            //         }
                    
            //         let json = JSON.stringify({
            //             touser: ownerInfo.data.wxOpenId,
            //             msgtype: "text",
            //             text: {
            //                 content: send_text
            //             }
            //             // "customservice":
            //             // {
            //             //     "kf_account": session && session.user.kf_account
            //             // }
            //         });

            //         let send_res = await api.post("/wx/customsend", { json });
            //     }
            // } else {
            //     // this.refs.toast.show('绑定的用户不存在');
            // }

            this.props.navigator.pop();
            let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                Emitter.emit("order.onload");

        }else{
            Toast.bottom("该笔订单已完成，请刷新后重试");
        }
    }

    _renderPrice = () => {
        return (
            <View style={styles.content}>
                <View
                    style={[
                        styles.formItem1,
                        {
                            borderBottomWidth: 0,
                            height: 90,
                            flex: 1,
                            flexDirection: "row",
                            alignItems: "flex-start",
                            alignContent:"flex-start"
                        }
                    ]}
                >
                    <Text
                        style={[
                            styles.leftText,
                            { marginLeft: 15, marginTop: 10 }
                        ]}
                    >
                        服务费用明细
                    </Text>
                    <TextInput
                        value={this.state.serviceCostDetail}
                        onChangeText={text => {
                            this.setState({ serviceCostDetail: text });
                        }}
                        style={[styles.itemRight, styles.otherContent]}
                        editable={true}
                        clearButtonMode={"while-editing"}
                        multiline={true}
                        underlineColorAndroid={"#ffffff"}
                        placeholder={"请输入服务费用的详细内容"}
                        placeholderTextColor={"#B5B5B5"}
                    />
                </View>
                <View
                    style={{ flex: 1, height: 15, backgroundColor: "#f3f3f3" }}
                />
                <Text style={[styles.titleStyle,{marginTop:10}]}>请输入服务金额</Text>
                <View style={styles.inputContent}>
                    <Text style={styles.subStyle}>¥</Text>
                    <TextInput
                        style={styles.inputStyle}
                        editable={true}
                        autoFocus={Platform.OS == "ios" ? true : false}
                        value={this.state.serviceCost}
                        ref={component => (this._inputComp = component)}
                        keyboardType={"numeric"}
                        clearButtonMode={"while-editing"}
                        underlineColorAndroid={"#ffffff"}
                        placeholder={""}
                        onChangeText={text => {
                            let { serviceCost } = this.state;
                            if (text && !/^\d+(\.\d{0,2})?$/.test(text)) {
                                this.setState({ serviceCost });
                                return;
                            }

                            this.setState({ serviceCost: text });
                        }}
                        placeholderTextColor={"#B5B5B5"}
                    />
                </View>
                <TouchableOpacity
                    disabled={this.state.btnDisabled}
                    onPress={this._submitAction.bind(this)}
                    style={styles.submitActionPhoneBtn}
                >
                    <Text style={styles.submitActionText}>确定</Text>
                </TouchableOpacity>
            </View>
        );
    };

    render() {
        let { session, order_info, message } = this.props;
        if (!session) {
            return null;
        }
        return (
            <View
                style={styles.wrapper}
                onStartShouldSetResponderCapture={e => {
                    const focusField = TextInput.State.currentlyFocusedField();
                    if (
                        focusField != null &&
                        e.nativeEvent.target != focusField
                    ) {
                        dismissKeyboard();
                    }
                }}
            >
                <ScrollView style={styles.container}>
                    <View
                        style={[
                            styles.formItem,
                            {
                                flex: 1,
                                borderBottomWidth: 0,
                                height: 44,
                                // alignItems: "flex-start",
                                justifyContent: "space-between",
                                backgroundColor: "#fff",
                                marginTop: 15
                            }
                        ]}
                    >
                        <Text style={[styles.leftText, { marginLeft: 15 }]}>
                            是否需要支付服务费用
                        </Text>
                        <Switch
                            onTintColor="#0090fa"
                            thumbTintColor="#0090fa"
                            value={this.state.isPay}
                            onValueChange={() => {
                                this.setState({ isPay: !this.state.isPay });
                            }}
                        />
                    </View>
                    {this.state.isPay ? (
                        this._renderPrice()
                    ) : (
                        <TouchableOpacity
                            disabled={this.state.btnDisabled}
                            onPress={this.confirmService}
                            style={[
                                styles.submitActionPhoneBtn,
                                { marginTop: 100 }
                            ]}
                        >
                            <Text style={styles.submitActionText}>确定</Text>
                        </TouchableOpacity>
                    )}
                </ScrollView>
                <ToastTip ref="toast" />
                <LoadingTip show={this.state.showLoading} />
            </View>
        );
    }
}

var connectHelper = require("../../services/connectHelper");
ServiceCompletion = connectHelper(state => state)(ServiceCompletion);

module.exports = ServiceCompletion;
